package com.ruoyi.common.utils.oss;


import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.ruoyi.common.config.TencentCosConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author zouhuu
 * @description 阿里云对象存储上传工具类
 * @date 2022/06/16 14:21:12
 */
@Slf4j
@Component
public class TencentOssUploadUtils {

    private static TencentCosConfig tenantCosConfig;


    /**
     * 使用构造方法注入配置信息
     */
    @Autowired
    public TencentOssUploadUtils(TencentCosConfig tenantCosConfig) {
        // 写死
        tenantCosConfig.setSecretId("AKID348BHKOSVagp0GXq9ymS10AOdtKmGsWB");
        tenantCosConfig.setSecretKey("lYL9yqiaUVVYap3JZxKiArfWwTtGfw34");
        tenantCosConfig.setBucketName("zhanshen0808-1304095019");
        tenantCosConfig.setRegion("ap-shanghai");
        tenantCosConfig.setUrl("https://zhanshen0808-1304095019.cos.ap-shanghai.myqcloud.com");
        TencentOssUploadUtils.tenantCosConfig = tenantCosConfig;
    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    public static String uploadFile(MultipartFile file) throws Exception {

        // 生成 OSSClient
        //OSS ossClient = new OSSClientBuilder().build(tenantCosConfig.getEndpoint(), tenantCosConfig.getSecretId(), tenantCosConfig.getSecretKey());
        COSClient cosClient = initCos();
        // 原始文件名称
        // String originalFilename = file.getOriginalFilename();
        String filename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        String filePath = getFilePath(filename);
        try {
            // 设置上传文件信息
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(file.getSize());
            PutObjectRequest putObjectRequest = new PutObjectRequest(tenantCosConfig.getBucketName(), filePath, inputStream, objectMetadata);

            // 上传文件
            cosClient.putObject(putObjectRequest);
            cosClient.setBucketAcl(tenantCosConfig.getBucketName(), CannedAccessControlList.PublicRead);
            return tenantCosConfig.getUrl() + "/" + filePath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return tenantCosConfig.getUrl() + "/" + filePath;
    }

    private static String getFilePath(String fileName){
        String filePath = "xinxun/";
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        filePath += UUID.randomUUID() + fileType;
        return filePath;
    }

    /**
     * 初始化COSClient
     * @return
     */
    private static COSClient initCos(){
        // 1 初始化用户身份信息（secretId, secretKey）
        BasicCOSCredentials credentials = new BasicCOSCredentials(tenantCosConfig.getSecretId(), tenantCosConfig.getSecretKey());
        // 2 设置 bucket 的区域, COS 地域的简称请参照
        Region region = new Region(tenantCosConfig.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 从 5.6.54 版本开始，默认使用了 https
        // clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        return new COSClient(credentials, clientConfig);
    }

}
 